package com.student.liu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.student.liu.entity.Asset;
import com.student.liu.entity.User;
import com.student.liu.exception.ServiceValidationException;
import com.student.liu.mapper.IAssetMapper;
import com.student.liu.service.IAssetService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("assetService")
public class AssetServiceImpl extends ServiceImpl<IAssetMapper,Asset> implements IAssetService {
    @Resource
    IAssetMapper assetMapper;
//    @Resource
//    IAssetService assetService;

    @Override
    public List<Asset> listAsset() {
        QueryWrapper<Asset> queryWrapper = new QueryWrapper();
        return list(queryWrapper);
    }

    @Override
    public IPage pageUserInfo(Integer pageIndex, Integer pageSize, Integer departmentId, String assetNo, String asset, Integer nav, Integer number, Date registertime) {
        Page page = new Page(pageIndex, pageSize);
        QueryWrapper<Asset> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("asset.id", "asset_no", "asset", "department.name", "nav", "number","registertime");

        if (departmentId != null && departmentId != 0) {
            userQueryWrapper.eq("department_id", departmentId);
        }
        if ((asset != null && !asset.equals(""))||(assetNo != null && !assetNo.equals(""))) {
            userQueryWrapper.and(warpper -> warpper.like("asset", asset)
                                                    .like("asset_no", assetNo));
        }
        return assetMapper.selectAssetJoinDetAndRolPage(page, userQueryWrapper);
    }

    @Override
    public String saveAsset(Asset asset) {
        QueryWrapper<Asset> queryWrapper = new QueryWrapper();
        queryWrapper.eq("asset", asset.getAsset())
                .ne("id", asset.getId());

        if (asset.getId() == 0) {
            //新增
            if (count(queryWrapper) > 0) {
                throw new ServiceValidationException("资产名已存在", 402);
            }
            if (assetMapper.insert(asset) == 0) {
                throw new ServiceValidationException("新增失败", 402);
            }
            log.info("新增资产后的ID：" + asset.getId());
            return "资产新增成功";
        } else {
            //修改
            if (!updateById(asset)) {
                throw new ServiceValidationException("修改失败，可能ID不存在", 402);
            }
            return "修改成功";
        }
    }

    @Override
    public void removeAsset(Integer id) {
        if (!removeById(id)) {
            throw new ServiceValidationException("移除失败，可能ID不存在", 402);
        }
    }
}
